﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

namespace Single.Json
{
    /// <summary>
    /// 序列化 JSON 工具
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 任意对象序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="retain">保留属性</param>
        /// <param name="ignore">忽略属性</param>
        /// <param name="turns">要转换的属性</param>
        /// <param name="dateTimeFormate">日期格式</param>
        /// <returns>返回数据</returns>
        public static string Serialize(this object obj, 
            string[] retain = null, 
            string[] ignore = null, 
            IDictionary<string, string> turns = null, 
            string dateTimeFormate = "yyyy'-'MM'-'dd' 'HH':'mm':'ss", 
            Formatting formatting = Formatting.None)
        {
            var settings = new JsonSerializerSettings();

            if (retain != null || ignore != null || turns != null)
            {
                // 设置序列化解析器
                settings.ContractResolver = new JsonCustomContractResolver(retain, ignore, turns);
            }

            // 设置序列化时间格式
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = dateTimeFormate;
            settings.Converters.Add(timeConverter);

            return JsonConvert.SerializeObject(obj, formatting, settings);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">要返回的类型</typeparam>
        /// <param name="obj">数据</param>
        /// <returns>返回对象</returns>
        public static T Deserialize<T>(string obj)
        {
            var settings = new JsonSerializerSettings();

            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            return JsonConvert.DeserializeObject<T>(obj, settings);
        }

        public static void JArrayAdd(object jars, Dictionary<string, object> dic)
        {
            var jarray = jars as JArray;

            JObject jo = new JObject();

            foreach (var d in dic)
            {
                jo.Add(new JProperty(d.Key, d.Value));
            }

            jarray.Add(jo);
        }
    }
}
